package cn.ztuo.bitrade.dao;


import cn.ztuo.bitrade.entity.ContractWallet;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.querydsl.QueryDslPredicateExecutor;
import org.springframework.data.repository.query.Param;

import java.math.BigDecimal;
import java.util.List;

public interface ContractWalletMapper extends JpaRepository<ContractWallet, String>, JpaSpecificationExecutor<ContractWallet>, QueryDslPredicateExecutor<ContractWallet> {
    List<ContractWallet > findAllByMemberId(Long id);

    ContractWallet findByMemberId(Long id);

    @Modifying
    @Query("update ContractWallet set balance = balance +:amount where id = :id " )
    int addwallet(@Param("id")Long id, @Param("amount")BigDecimal amount);

    @Modifying
    @Query("update ContractWallet wallet set wallet.balance = wallet.balance - :amount where wallet.id = :id and wallet.balance >= :amount ")
    int decreaseBalance(@Param("id")Long id, @Param("amount")BigDecimal amount);

    @Modifying
    @Query("update ContractWallet wallet set wallet.balance = wallet.balance - :sub + :proxide , wallet.frozenBalance = wallet.frozenBalance + :sub where wallet.memberId  = :id" )
    void findByBalancedongjie(@Param("id")Long memberId,  @Param("sub")BigDecimal sub ,@Param("proxide")BigDecimal proxide);

    /**
     * 解冻钱包余额
     *
     * @param walletId
     * @param amount
     * @return
     */
    @Modifying
    @Query("update ContractWallet wallet set wallet.balance = wallet.balance + :amount,wallet.frozenBalance=wallet.frozenBalance - :amount where wallet.id = :walletId and wallet.frozenBalance >= :amount")
    int thawBalance(@Param("walletId") Long walletId, @Param("amount") BigDecimal amount);

    /**
     * 冻结钱包余额
     *
     * @param id
     * @param sub
     * @return
     */
    @Modifying
    @Query("update ContractWallet wallet set wallet.balance = wallet.balance - :sub,wallet.frozenBalance=wallet.frozenBalance + :sub where wallet.id = :id and wallet.balance >= :sub")
    int addfrozenBalance(@Param("id")Long id, @Param("sub")BigDecimal sub);

    /**
     * 减少冻结余额
     *
     * @param walletId
     * @param amount
     * @return
     */
    @Modifying
    @Query("update ContractWallet wallet set wallet.frozenBalance=wallet.frozenBalance - :amount where wallet.id = :walletId and wallet.frozenBalance >= :amount")
    int decreaseFrozen(@Param("walletId") long walletId, @Param("amount") BigDecimal amount);
}
